package com.tencent.iov.cowin.befsale.clue.service.cus.impl;

import com.alibaba.fastjson.JSON;
import com.google.common.collect.Lists;
import com.software.boot.common.entity.Response;
import com.software.boot.common.exception.BusinessException;
import com.software.boot.common.exception.NEError;
import com.software.boot.common.model.dao.OrderField;
import com.software.boot.common.util.*;
import com.software.common.config.SearchLocalHeader;
import com.software.common.enums.DeleteEnum;
import com.software.common.enums.SCRMRequestHeaderEnum;
import com.software.common.utils.BasePropertyInjection;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.assembler.ClueCustomerCollectAssembler;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueIntentionResponse;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueOrderResponse;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueResponse;
import com.tencent.iov.cowin.befsale.clue.controller.clue.vo.response.ClueToMqVehResponse;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.request.*;
import com.tencent.iov.cowin.befsale.clue.controller.cus.vo.response.*;
import com.tencent.iov.cowin.befsale.clue.dao.http.log.EtlLogClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.log.request.*;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.MdQueryClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryCertificateInfoRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.request.QueryVehicleModelRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.CertificateInfoResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.DealerResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdquery.response.VehicleModelResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdwrite.MdWriteClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdwrite.request.AddCertificateInfoRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.mdwrite.request.UpdateCertificateInfoRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.TenantClient;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.request.QueryDictionariesRequest;
import com.tencent.iov.cowin.befsale.clue.dao.http.tenant.response.DictionariesResponse;
import com.tencent.iov.cowin.befsale.clue.dao.http.todo.request.CustomButtonRequest;
import com.tencent.iov.cowin.befsale.clue.domain.clue.po.*;
import com.tencent.iov.cowin.befsale.clue.domain.cus.po.PurchaseInvoiceInfo;
import com.tencent.iov.cowin.befsale.clue.repository.cus.DealerCustomerManager;
import com.tencent.iov.cowin.befsale.clue.repository.cus.OemCustomerManager;
import com.tencent.iov.cowin.befsale.clue.repository.cus.PurchaseInvoiceInfoManager;
import com.tencent.iov.cowin.befsale.clue.service.clue.*;
import com.tencent.iov.cowin.befsale.clue.service.cus.*;
import com.tencent.iov.cowin.befsale.clue.service.tenant.DictionaryService;
import com.tencent.iov.cowin.befsale.clue.value.enums.*;
import com.tencent.iov.cowin.befsale.clue.value.utils.CustomerUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.collections4.ListUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Author xiamu
 * @Date 2021/12/24 9:34
 * @Version 1.0
 **/
@Service
@Slf4j
@RefreshScope
public class ClueCustomerDetailServiceImpl implements ClueCustomerDetailService {

    @Autowired
    private ClueService clueService;
    @Lazy
    @Autowired
    private CustomerService customerService;
    @Autowired
    private CustomerFollowPlanService customerFollowPlanService;
    @Autowired
    private CustomerFollowRecordService customerFollowRecordService;
    @Autowired
    private ClueIntentionService clueIntentionService;
    @Autowired
    private OemCustomerService oemCustomerService;
    @Autowired
    private ClueCustomerCollectService clueCustomerCollectService;
    @Autowired
    private ClueOrderService clueOrderService;
    @Autowired
    private ClueFailService clueFailService;
    @Autowired
    private MdQueryClient mdQueryClient;
    @Autowired
    private EtlLogClient etlLogClient;
    @Autowired
    private ClueIntentionVehicleService clueIntentionVehicleService;
    @Autowired
    private TenantClient tenantClient;
    @Autowired
    private DealerCustomerManager dealerCustomerManager;
    @Autowired
    private OemCustomerManager oemCustomerManager;
    @Autowired
    private PurchaseInvoiceInfoManager purchaseInvoiceInfoManager;
    @Autowired
    private ClueTodoRelService clueTodoRelService;
    @Autowired
    private MdWriteClient writeClient;
    //代办配置时间 添加好友
    @Value("${clue-todo.time.add-friend}")
    private Integer addFriend;

    @Value("${clue-todo.template.msgTodoAddFriend.id}")
    private Long addFriendTodoId;

    @Value("${clue-todo.template.msgTodoFollowClue.id}")
    private Long followTodoId;

    @Autowired
    private DictionaryService dictionaryService;

    @Value("${properties.intention.grade.type:}")
    private String intentionGradeType;

    @Override
    public ClueDetailResponse getClueDetail(QueryClueDetailRequest request) {
        ValidateUtils.checkObjNull(request, "参数为null");
        if (EmptyUtils.isEmpty(request.getClueId()) && EmptyUtils.isEmpty(request.getExternalUserId())) {
            throw new BusinessException(NEError.INVALID_PARAMETER, "线索ID与外部联系人ID不可以全为null");
        }

        ClueDetailResponse clueDetailResponse = new ClueDetailResponse();

        //填充线索基本信息
        Clue clue = getClueInfo(request);
        if (EmptyUtils.isEmpty(clue)) {
            throw new BusinessException(NEError.INVALID_PARAMETER, "线索信息不存在");
        }
        ClueResponse clueResponse = BeanUtil.copy(clue, ClueResponse.class);
        clueDetailResponse.setClueInfo(clueResponse);

        //填充意向信息
        fillClueIntention(clueDetailResponse);

        //填充订单信息
        fillClueOrder(clueDetailResponse);

        //判断线索是否存在客户信息
        if (EmptyUtils.isEmpty(clue.getCusId())) {
            return clueDetailResponse;
        }

        //填充客户与跟进信息
        fillCustomerInfoAndFollowInfo(clueDetailResponse);

        //填充证件和发票信息
        fillCertificatesAndInvoiceInfo(clueDetailResponse);

        return clueDetailResponse;
    }

    private void fillCertificatesAndInvoiceInfo(ClueDetailResponse clueDetailResponse) {
        if (clueDetailResponse.getCustomerInfo() != null && clueDetailResponse.getCustomerInfo().getOneId() != null) {
            QueryCertificateInfoRequest queryCertificateInfoRequest = new QueryCertificateInfoRequest();
            queryCertificateInfoRequest.setOneId(Long.valueOf(clueDetailResponse.getCustomerInfo().getOneId()));
            queryCertificateInfoRequest.setDeleted(DeleteEnum.INIT.getFlag());
            List<CertificateInfoResponse> data = mdQueryClient.getListByParam(queryCertificateInfoRequest).getData();
            clueDetailResponse.setCertificateInfos(data);
        }
        if (clueDetailResponse.getClueOrder() != null && clueDetailResponse.getClueOrder().getId() != null) {
            PurchaseInvoiceInfo queryPurchaseInvoiceInfo = new PurchaseInvoiceInfo();
            queryPurchaseInvoiceInfo.setDeleted(DeleteEnum.INIT.getFlag());
            queryPurchaseInvoiceInfo.setOrderId(clueDetailResponse.getClueOrder().getId());
            clueDetailResponse.setPurchaseInvoiceInfo(purchaseInvoiceInfoManager.getOneByParam(queryPurchaseInvoiceInfo));
        }
    }

    private Clue getClueInfo(QueryClueDetailRequest request) {
        if (EmptyUtils.isNotEmpty(request.getClueId()) && request.getClueId() > 0) {
            return clueService.getDetailById(request.getClueId());
        }
        ValidateUtils.checkObjNull(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode()), "成员ID参数为null");
        Long empId = Long.parseLong(SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode()));
        ValidateUtils.checkLongGTZero(empId, "人员信息不存在");
        return clueService.getDetailByExternalUserIdAndFollowEmpId(request.getExternalUserId(), empId);
    }

    private void fillClueIntention(ClueDetailResponse clueDetailResponse) {
        ClueResponse clueResponse = clueDetailResponse.getClueInfo();
        ClueIntention request = new ClueIntention();
        request.setClueId(clueResponse.getId());
        request.setDeleted(DeleteEnum.INIT.getFlag());
        request.setOrderFields(Lists.newArrayList(new OrderField("id", "DESC")));
        ClueIntentionResponse clueIntention = clueIntentionService.getOneByParam(request);
        if (EmptyUtils.isEmpty(clueIntention)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "意向信息 不可以为null");
        }
        clueIntention.setIntentionGrade(clueResponse.getIntentionGrade());
        clueDetailResponse.setClueIntention(clueIntention);
    }

    private void fillCustomerInfoAndFollowInfo(ClueDetailResponse clueDetailResponse) {
        ClueResponse clueResponse = clueDetailResponse.getClueInfo();
        //获取客户信息
        clueDetailResponse.setCustomerInfo(customerService.getDetailByIdAndDealerId(clueResponse.getCusId(), clueResponse.getDealerId()));

        //获取最近一下跟进计划信息
        clueDetailResponse.setFollowPlan(getCustomerFollowPlan(clueResponse));

        QueryCustomerFollowRecordRequest followRecordRequest = new QueryCustomerFollowRecordRequest();
        //有活跃线索直接显示活跃内容
        if(clueDetailResponse.getClueInfo().getIsActive() == IsActiveEnum.ACTIVE_YES.getCode()){
            //获取线索 跟进历史信息与本次跟进信息
            followRecordRequest = QueryCustomerFollowRecordRequest.builder()
                    .clueId(clueResponse.getId())
                    .deleted(DeleteEnum.INIT.getFlag())
                    .build();
        }else{
            //获取客户已有跟进历史
            followRecordRequest = QueryCustomerFollowRecordRequest.builder()
                    .cusId(clueResponse.getCusId())
                    .deleted(DeleteEnum.INIT.getFlag())
                    .build();
        }


        OrderField recordOrderField = new OrderField("id", "DESC");
        followRecordRequest.setOrderFields(Lists.newArrayList(recordOrderField));
        List<CustomerFollowRecordResponse> followRecords = customerFollowRecordService.getListByParam(followRecordRequest);
        if (EmptyUtils.isNotEmpty(followRecords)) {
            clueDetailResponse.setFollowRecordList(followRecords);
            clueDetailResponse.setFollowRecord(followRecords.get(0));
        }
    }

    private CustomerFollowPlanResponse getCustomerFollowPlan(ClueResponse clueResponse) {
        QueryCustomerFollowPlanRequest followPlanRequest = QueryCustomerFollowPlanRequest.builder()
                .clueId(clueResponse.getId())
                .status(FollowPlanStatusEnum.WAIT_FOLLOW.getCode())
                .deleted(DeleteEnum.INIT.getFlag())
                .build();
        OrderField planOrderField = new OrderField("id", "DESC");
        followPlanRequest.setOrderFields(Lists.newArrayList(planOrderField));
        CustomerFollowPlanResponse customerFollowPlan = customerFollowPlanService.getOneByParam(followPlanRequest);
        //创建、分配、验证、审批不展示
        if (EmptyUtils.isEmpty(customerFollowPlan)
                || EmptyUtils.isEmpty(customerFollowPlan.getPlanFollowContent())) {
            return null;
        }
        return customerFollowPlan;
    }

    private void fillClueOrder(ClueDetailResponse clueDetailResponse) {
        //获取下定信息
        ClueOrder orderQueryRequest = new ClueOrder();
        orderQueryRequest.setClueId(clueDetailResponse.getClueInfo().getId());
        orderQueryRequest.setDeleted(DeleteEnum.INIT.getFlag());
        OrderField orderField = new OrderField("id", "desc");
        orderQueryRequest.setOrderFields(Lists.newArrayList(orderField));
        clueDetailResponse.setClueOrder(clueOrderService.getOneByParam(orderQueryRequest));
    }

    @Override
    @Transactional(transactionManager = "qw_sale_mastertx", rollbackFor = Exception.class)
    public Boolean updateClueCustomerDetail(UpdateClueCustomerRequest request) {
        ValidateUtils.checkObjNull(request, "参数为null");
        if (EmptyUtils.isEmpty(request.getUpdateClueIntention()) && EmptyUtils.isEmpty(request.getUpdateCustomer())) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_INVALIDATE, "意向与客户信息不可以全为null");
        }

        //更新线索与意向信息
        if (EmptyUtils.isNotEmpty(request.getUpdateClueIntention())) {
            clueService.updateClueAndIntention(request.getUpdateClueIntention());
        }

        if (EmptyUtils.isEmpty(request.getUpdateCustomer())) {
            return true;
        }

        //更新客户信息
        customerService.updateCustomerInfo(request.getUpdateCustomer());

        //更新线索宽表信息 bef_clue_customer_collect
        clueCustomerCollectService.updateClueCustomerCollect(request);
        return true;
    }

    @Override
    @Transactional(transactionManager = "qw_sale_mastertx", rollbackFor = Exception.class)
    public Boolean saveClueCustomerFollowInfoByParam(AddClueCustomerFollowRequest request) {
        ValidateUtils.checkObjNull(request, "跟进信息参数为null");
        if (EmptyUtils.isEmpty(request.getAddCustomerFollowPlan()) && EmptyUtils.isEmpty(request.getAddCustomerFollowRecord())) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "跟进记录与跟进计划不可以全为null");
        }
        Long cusId = EmptyUtils.isEmpty(request.getAddCustomerFollowPlan()) ? request.getAddCustomerFollowRecord().getCusId() : request.getAddCustomerFollowPlan().getCusId();
        ValidateUtils.checkLongGTZero(cusId, "cusId参数不可以为null");
        //获取客户信息
        CustomerResponse customerResponse = customerService.getDetailByIdAndDealerId(cusId, null);
        if (EmptyUtils.isEmpty(customerResponse)) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "客户信息不存在");
        }

        //校验操作人是否是跟进人
        String empId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        String followEmpId = customerResponse.getFollowEmpId().toString();
        if (EmptyUtils.isNotEmpty(customerResponse.getFollowEmpId()) && !followEmpId.equals(empId)) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "线索信息不在该账户跟进下");
        }

        //保存跟进计划信息
        Long followPlanId = null;
        if (EmptyUtils.isNotEmpty(request.getAddCustomerFollowPlan())) {
            AddCustomerFollowPlanRequest followPlanRequest = request.getAddCustomerFollowPlan();
            followPlanId = customerFollowPlanService.insert(followPlanRequest);
            followPlanRequest.setId(followPlanId);
            request.setAddCustomerFollowPlan(followPlanRequest);
        }
        //创建添加好友代办
        makeAddFriendTodoTask(request, customerResponse, empId);
        //处理跟进内容信息
        Long orderId = dealCustomerFollowRecord(request, followPlanId);

        //更新线索宽表信息 bef_clue_customer_collect
        clueCustomerCollectService.updateByFollowInfo(request);

        //处理试乘试驾存的身份证/驾驶证信息
        processCertificateInfo(request);

        //处理交车存的身份证/发票信息
        processOrderInfo(request);

        //查询是否已有代办，有代办更新为完成
        clueTodoRelService.updateClueTodoTask(MsgTodoEnum.FOLLOW_CLUE.getCode(), request.getAddCustomerFollowRecord().getClueId(), empId);

        //若有下次跟进时间就对接待办
        if(Objects.nonNull(request.getAddCustomerFollowPlan()) && Objects.nonNull(request.getAddCustomerFollowPlan().getPlanFollowTime())){
            //创建跟进代办
            processFollowTodoParam(request, customerResponse, empId);
        }

        return true;
    }

    private void processOrderInfo(AddClueCustomerFollowRequest request) {
        log.info("处理发票信息");
        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
        AddCustomerFollowRecordRequest followRecord = request.getAddCustomerFollowRecord();

        if (FollowContentEnum.DELIVERY.getCode().toString().equals(followRecord.getFollowContent())) {
            //查询线索的订单
            if(request.getAddCustomerFollowRecord().getClueId() == null){
                throw new BusinessException(NEError.BUSINESS_ERROR, "处理交车证件信息和发票信息时，跟进记录的线索ID为空");
            }
            ClueOrder orderParam = new ClueOrder();
            orderParam.setClueId(request.getAddCustomerFollowRecord().getClueId());
            orderParam.setDeleted(DeleteEnum.INIT.getFlag());

            ClueOrderResponse clueOrder = clueOrderService.getOneByParam(orderParam);
            if(clueOrder == null){
                throw new BusinessException(NEError.BUSINESS_ERROR, "处理交车证件信息和发票信息时，查询订单信息为空");
            }
            Long orderId = clueOrder.getId();

            List<AddCertificateInfoRequest> certificateInfos = followRecord.getCertificateInfos();
            for (AddCertificateInfoRequest certificateInfo : ListUtils.emptyIfNull(certificateInfos)) {
                if (certificateInfo != null) {
                    //处理身份证信息
                    CustomerResponse customer = null;
                    if (dealerId != null) {
                        customer  = BeanUtil.copy(dealerCustomerManager.getDetailById(request.getAddCustomerFollowRecord().getCusId()), CustomerResponse.class);
                    } else {
                        customer = BeanUtil.copy(oemCustomerManager.getDetailById(request.getAddCustomerFollowRecord().getCusId()), CustomerResponse.class);
                    }
                    if (customer != null) {
                        //存在即更新，反之新增
                        certificateInfo.setOneId(Long.valueOf(customer.getOneId()));
                        certificateInfo.setCusId(customer.getCustomerBaseId());
                        certificateInfo.setDataSources(CertificateEnum.FORM_IMPORT.getCode());

                        QueryCertificateInfoRequest queryCertificateInfoRequest = new QueryCertificateInfoRequest();
                        queryCertificateInfoRequest.setOneId(Long.valueOf(customer.getOneId()));
                        queryCertificateInfoRequest.setDeleted(DeleteEnum.INIT.getFlag());
                        queryCertificateInfoRequest.setCertificateType(CertificateEnum.ID_CARD.getCode());
                        log.info("调用mdQuery 查询证件表,入参：{}", JsonUtils.object2JSON(queryCertificateInfoRequest));
                        CertificateInfoResponse certificateInfoResponse = mdQueryClient.getOneByParam(queryCertificateInfoRequest).getData();
                        if (certificateInfoResponse != null) {
                            Long id = certificateInfoResponse.getId();
                            certificateInfo.setId(id);
                            BasePropertyInjection.updatePropertyInjection(certificateInfo);
                            log.info("调用mdWrite update证件表,入参：{}", JsonUtils.object2JSON(certificateInfo));
                            writeClient.update(BeanUtil.copy(certificateInfo, UpdateCertificateInfoRequest.class));
                        } else {
                            BasePropertyInjection.savePropertyInjection(certificateInfo);
                            log.info("调用mdWrite add证件表,入参：{}", JsonUtils.object2JSON(certificateInfo));
                            writeClient.add(certificateInfo);
                        }
                    }
                }
            }

            PurchaseInvoiceInfo invoiceInfo = followRecord.getPurchaseInvoiceInfo();
            if (invoiceInfo != null) {
                invoiceInfo.setOrderId(orderId);

                //处理发票信息
                PurchaseInvoiceInfo queryPurchaseInvoiceInfo = new PurchaseInvoiceInfo();
                queryPurchaseInvoiceInfo.setDeleted(DeleteEnum.INIT.getFlag());
                queryPurchaseInvoiceInfo.setOrderId(orderId);
                PurchaseInvoiceInfo param = purchaseInvoiceInfoManager.getOneByParam(queryPurchaseInvoiceInfo);
                if (param != null) {
                    invoiceInfo.setId(param.getId());
                    BasePropertyInjection.updatePropertyInjection(invoiceInfo);
                    purchaseInvoiceInfoManager.update(invoiceInfo);
                } else {
                    BasePropertyInjection.savePropertyInjection(invoiceInfo);
                    purchaseInvoiceInfoManager.insert(invoiceInfo);
                }
            }
        }
    }

    private void processCertificateInfo(AddClueCustomerFollowRequest request) {
        log.info("处理证件表信息");
        String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
        AddCustomerFollowRecordRequest followRecord = request.getAddCustomerFollowRecord();
        if (FollowContentEnum.DRIVE_TEST.getCode().toString().equals(followRecord.getFollowContent())) {
            List<AddCertificateInfoRequest> certificateInfos = followRecord.getCertificateInfos();
            if (CollectionUtils.isNotEmpty(certificateInfos)) {
                for (AddCertificateInfoRequest certificateInfo : certificateInfos) {
                    CustomerResponse customer = null;
                    if (dealerId != null) {
                        customer  = BeanUtil.copy(dealerCustomerManager.getDetailById(request.getAddCustomerFollowPlan().getCusId()), CustomerResponse.class);
                    } else {
                        customer = BeanUtil.copy(oemCustomerManager.getDetailById(request.getAddCustomerFollowPlan().getCusId()), CustomerResponse.class);
                    }
                    if (customer != null) {
                        certificateInfo.setOneId(Long.valueOf(customer.getOneId()));
                        certificateInfo.setCusId(customer.getCustomerBaseId());
                        certificateInfo.setDataSources(CertificateEnum.FORM_IMPORT.getCode());
                        QueryCertificateInfoRequest queryCertificateInfoRequest = new QueryCertificateInfoRequest();
                        queryCertificateInfoRequest.setOneId(Long.valueOf(customer.getOneId()));
                        queryCertificateInfoRequest.setDeleted(DeleteEnum.INIT.getFlag());
                        queryCertificateInfoRequest.setCertificateType(certificateInfo.getCertificateType());
                        log.info("调用mdQuery 查询证件表,入参：{}", JsonUtils.object2JSON(queryCertificateInfoRequest));
                        CertificateInfoResponse certificateInfoResponse = mdQueryClient.getOneByParam(queryCertificateInfoRequest).getData();
                        if (certificateInfoResponse != null) {
                            Long id = certificateInfoResponse.getId();
                            certificateInfo.setId(id);
                            BasePropertyInjection.updatePropertyInjection(certificateInfo);
                            log.info("调用mdWrite update证件表,入参：{}", JsonUtils.object2JSON(certificateInfo));
                            writeClient.update(BeanUtil.copy(certificateInfo, UpdateCertificateInfoRequest.class));
                        } else {
                            BasePropertyInjection.savePropertyInjection(certificateInfo);
                            log.info("调用mdWrite add证件表,入参：{}", JsonUtils.object2JSON(certificateInfo));
                            writeClient.add(certificateInfo);
                        }
                    }
                }
            }
        }
    }

    private void makeAddFriendTodoTask(AddClueCustomerFollowRequest request, CustomerResponse customerResponse, String empId) {
        //判断是否首次跟进
        Boolean isFirst = judgeFirstFollow(request, empId);
        //判断是否已添加好友
        if(isFirst) {
            String dealerId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_DEALER_ID.getCode());
            CustomerResponse customerRes = customerService.getDetailByIdAndDealerId(request.getAddCustomerFollowRecord().getCusId(), dealerId);
            if (customerRes != null && customerRes.getBindTime() != null && customerRes.getExternalUserid() != null) {
                isFirst = false;
            }
        }

        if(isFirst) {
            List<Long> empIds = new ArrayList<>();

            Date date = DateUtil.addHours(new Date(), addFriend);
            empIds.add(Long.valueOf(empId));
            Map<String, Object> todoMap = new HashMap<>();
            String name = customerResponse.getName();
            String phone = customerResponse.getPhone();
            todoMap.put("name", name);
            todoMap.put("phone", phone);
            List<CustomButtonRequest> buttonRequestList = new ArrayList<>();

            CustomButtonRequest customButtonRequest = new CustomButtonRequest();
            customButtonRequest.setName(MsgTodoEnum.BTN_ADD_FRIEND.getName());
            customButtonRequest.setEvent(MsgTodoEnum.BTN_ADD_FRIEND.getCode());
            customButtonRequest.setType(2);

            buttonRequestList.add(customButtonRequest);
            CustomButtonRequest customButtonRequest1 = new CustomButtonRequest();
            customButtonRequest1.setName(MsgTodoEnum.BTN_BIND_FRIENDS_PRESALES.getName());
            customButtonRequest1.setEvent(MsgTodoEnum.BTN_BIND_FRIENDS_PRESALES.getCode());
            customButtonRequest1.setType(2);
            buttonRequestList.add(customButtonRequest1);

            String title = "待添加好友-" + name;
            String content = "客户:" + name + "|" + phone;

            clueFailService.makeTodoTask(buttonRequestList, addFriendTodoId, title, content, MsgTodoEnum.ADD_FRIEND.getCode(), empIds, todoMap, date, request.getAddCustomerFollowRecord().getClueId(), phone,null,null,null);
        }
    }

    /**
     * 判断是否首次跟进  true是首次，false不是首次
     * @param request
     * @param empId
     * @return
     */
    private Boolean judgeFirstFollow(AddClueCustomerFollowRequest request, String empId) {
        Boolean isFirst = true;
        QueryCustomerFollowRecordRequest followRecordRequest = new QueryCustomerFollowRecordRequest();
        followRecordRequest.setDeleted(DeleteEnum.INIT.getFlag());
        followRecordRequest.setClueId(request.getAddCustomerFollowRecord().getClueId());
        followRecordRequest.setFollowEmpId(Long.valueOf(empId));
        List<CustomerFollowRecordResponse> recordResponseList = customerFollowRecordService.getListByParam(followRecordRequest);
        if (CollectionUtils.isNotEmpty(recordResponseList)) {
            for (CustomerFollowRecordResponse recordResponse : recordResponseList) {
                if (FollowRecordStatusEnum.FOLLOW_UP.getCode().equals(recordResponse.getStatus())) {
                    isFirst = false;
                    break;
                }
            }
        }
        return isFirst;
    }

    private void processFollowTodoParam(AddClueCustomerFollowRequest request, CustomerResponse customerResponse, String empId) {
        List<Long> empIds = new ArrayList<>();
        Date date = DateUtil.addHours(new Date(), 24);

        if (request.getAddCustomerFollowPlan() != null && request.getAddCustomerFollowPlan().getPlanFollowTime() != null) {
            date = request.getAddCustomerFollowPlan().getPlanFollowTime();
        }
        empIds.add(Long.valueOf(empId));

        String name = customerResponse.getName();
        String phone = customerResponse.getPhone();
        String followContent = request.getAddCustomerFollowPlan() == null ? null : request.getAddCustomerFollowPlan().getPlanFollowContent();
        String content = followContent == null ? "产品介绍" : FollowContentEnum.getDictionaries(Integer.valueOf(followContent));

        clueService.makeFollowTodoTask(date, empIds, content, name, phone, request.getAddCustomerFollowRecord().getClueId(),null,null,customerResponse.getExternalUserid());
    }

    private Long dealCustomerFollowRecord(AddClueCustomerFollowRequest request, Long followPlanId) {
        if (EmptyUtils.isEmpty(request.getAddCustomerFollowRecord())) {
            return null;
        }
        AddCustomerFollowRecordRequest recordRequest = request.getAddCustomerFollowRecord();
        recordRequest.setNextFollowPlanId(followPlanId);

        //更新线索状态
        updateClueInfo(recordRequest);

        //下订、交车业务
        Long orderId = clueOrderBusiness(recordRequest);
        recordRequest.setOrderId(orderId);

        customerFollowRecordService.insert(recordRequest);
        return orderId;

    }

    private Long clueOrderBusiness(AddCustomerFollowRecordRequest request) {
        //下订
        if (FollowContentEnum.ORDER.getCode().toString().equals(request.getFollowContent())) {
            return clueOrderService.insertOrUpdateClueOrder(request.getClueOrder());
        }
        //交车
        if (FollowContentEnum.DELIVERY.getCode().toString().equals(request.getFollowContent())) {
            return clueOrderService.deliveryCar(request.getClueId());
        }

        return 0L;
    }

    private void updateClueInfo(AddCustomerFollowRecordRequest recordRequest) {
        Clue existClue = clueService.getDetailById(recordRequest.getClueId());
        if (StringUtils.equals(recordRequest.getFollowContent(), FollowContentEnum.ORDER.getCode().toString())) {
            //如果下訂的话，意向等级强制为O
            List<DictionariesResponse> dictionariesResponseList = dictionaryService.listDictionary(intentionGradeType);
            DictionariesResponse dictionariesResponse = dictionariesResponseList.stream().filter(d -> d.getName().startsWith("O")).findFirst().orElse(null);
            if (dictionariesResponse != null) {
                existClue.setIntentionGrade(dictionariesResponse.getCode());
            }
        }
        ValidateUtils.checkObjNull(existClue, "线索信息不存在");
        Clue updateClue = ClueAssembler.initUpdateByFollowInfo(recordRequest, existClue);
        if (EmptyUtils.isEmpty(updateClue)) {
            return;
        }
        int updateClueResult = clueService.update(updateClue);
        if (updateClueResult <= 0) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_INVALIDATE, "参数为null");
        }
    }

    @Override
    @Transactional(transactionManager = "qw_sale_mastertx", rollbackFor = Exception.class)
    public Boolean updateClueFollowEmp(UpdateClueEmpRequest request) {
        //校验参数
        ValidateUtils.checkObjNull(request, "分配顾问-参数为null");
        ValidateUtils.checkObjNull(request.getClueIds(), "分配顾问-线索列表为null");
        ValidateUtils.checkObjNull(request.getFollowEmpId(), "分配顾问-顾问ID为null");
        if (!CustomerUtil.isDealer()) {
            throw new BusinessException(NEError.INVALID_PARAMETER, "分配顾问-总部暂不支持此功能");
        }

        //处理传入数据出现重复情况
        List<Long> clueIds = request.getClueIds().stream().distinct().collect(Collectors.toList());
        request.setClueIds(clueIds);

        Clue clue = new Clue();
        clue.setIds(clueIds);
        clue.setDeleted(DeleteEnum.INIT.getFlag());
        List<Clue> clues = clueService.getListByParam(clue);
        if (EmptyUtils.isEmpty(clues) || clues.size() < request.getClueIds().size()) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索信息不存在");
        }

        List<Clue> notSupports = clues.stream().filter( sClue ->
        ClueStatsEnum.CONSUMED.getCode().equals(sClue.getStatus()) || ClueStatsEnum.IS_FAIL.getCode().equals(sClue.getStatus())).collect(Collectors.toList());
        if (EmptyUtils.isNotEmpty(notSupports)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "存在不支持状态的的线索");
        }

        //更新线索
        clue = ClueAssembler.initUpdateByDistribute(request);
        int clueResult = clueService.updateByIds(clue);
        if (clueResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "更新线索表失败");
        }

        //更新客户跟进人信息
        Map<Long, CustomerResponse> customerMap = customerService.distributeCustomers(request, clues);
        if (EmptyUtils.isEmpty(customerMap)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索分配- 客户信息不存在");
        }

        //保存分配跟进记录
        customerFollowRecordService.insertBatchByDistribute(clues, request, customerMap);

        //更新线索宽表
        updateClueCustomerCollectByDistribute(request);

        //查询是否有待办，完成待分配待办
        String empId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        log.info("分配跟进人，获取header的empId：【{}】",empId);
        if(StringUtils.isNotBlank(empId)){
            for (Long clueId :
                    clueIds) {
                clueTodoRelService.updateClueTodoTask(MsgTodoEnum.ASSIGN_CLUE.getCode(),clueId,empId);
            }

        }
        return true;
    }

    private void updateClueCustomerCollectByDistribute(UpdateClueEmpRequest request) {
        ClueCustomerCollect collectRequest = new ClueCustomerCollect();
        collectRequest.setClueIds(request.getClueIds());
        collectRequest.setDeleted(DeleteEnum.INIT.getFlag());
        List<ClueCustomerCollect> customerCollects = clueCustomerCollectService.getListByParam(collectRequest);
        if (EmptyUtils.isEmpty(customerCollects) && request.getClueIds().size() > customerCollects.size()) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索客户宽表信息不存在");
        }

        List<Long> collectIds = customerCollects.stream().map(ClueCustomerCollect::getId).collect(Collectors.toList());
        ClueCustomerCollect updateCollectRequest = ClueCustomerCollectAssembler.initUpdateByDistributeInfo(request);
        updateCollectRequest.setIds(collectIds);
        Integer result = clueCustomerCollectService.updateByIds(updateCollectRequest);
        ValidateUtils.checkIntGTZero(result, "更新线索宽表数据信息失败");
    }

    @Override
    @Transactional(transactionManager = "qw_sale_mastertx", rollbackFor = Exception.class)
    public Boolean updateFailClueFollow(UpdateClueEmpRequest request) {
        //校验参数
        ValidateUtils.checkObjNull(request, "参数为null");
        ValidateUtils.checkLongGTZero(request.getClueId(), "战败审批-线索ID不可以为null");
        ValidateUtils.checkIntGTZero(request.getFailStatus(), "战败审批-战败状态不可以为null");

        Clue clue = clueService.getDetailById(request.getClueId());
        if (EmptyUtils.isEmpty(clue) || DeleteEnum.DETELED.getFlag().equals(clue.getDeleted())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-线索信息不存在");
        }
        if (!FailStatusEnum.ACTIVATE.getCode().equals(request.getFailStatus()) && EmptyUtils.isNotEmpty(clue.getIsActive()) && IsActiveEnum.ACTIVE_NO.getCode().equals(clue.getIsActive())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-活跃线索信息不存在");
        }

        //战败激活校验是否已存在
        checkFailActive(request, clue);

        //更新线索战败信息
        ClueFail clueFail = clueFailService.updateByFailInfo(request);

        //更新线索
        ClueAssembler.initUpdateByFailClue(request, clueFail, clue);
        int clueResult = clueService.update(clue);
        if (clueResult <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-更新线索表失败");
        }

        //战败审批-客户信息分配 拒绝、激活操作跟进人信息 同意直接返回客户信息
        CustomerResponse customerResponse = customerService.distributeCustomer(request, clue);
        if (EmptyUtils.isEmpty(customerResponse)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-客户信息不存在");
        }

        ///战败审批-跟进计划 - 同意更新跟进信息为已取消 激活-保存产品介绍
        CustomerFollowPlanResponse followPlanResponse = customerFollowPlanService.insertOrUpdateByFailClue(clue, request);

        //战败审批-跟进记录 同意、拒绝、激活
        Long planId = EmptyUtils.isEmpty(followPlanResponse) ? null : followPlanResponse.getId();
        request.setPlanFollowId(planId);
        customerFollowRecordService.insertByFailClue(clue, request, customerResponse, clueFail);

        //更新线索宽表
        updateClueCustomerCollectByClueFailInfo(request, followPlanResponse, clueFail);

        //处理线索审批代办任务
        String empId = SearchLocalHeader.getHeader(SCRMRequestHeaderEnum.HEADER_EMP_ID.getCode());
        clueTodoRelService.updateClueTodoTask(MsgTodoEnum.EXAMINE_CLUE.getCode(), request.getClueId(), empId);

        return true;
    }

    private void updateClueCustomerCollectByClueFailInfo(UpdateClueEmpRequest request, CustomerFollowPlanResponse followPlanResponse, ClueFail clueFail) {
        ClueCustomerCollect collectRequest = new ClueCustomerCollect();
        collectRequest.setClueId(request.getClueId());
        collectRequest.setDeleted(DeleteEnum.INIT.getFlag());
        collectRequest.setOrderFields(Lists.newArrayList(new OrderField("id", "DESC")));
        ClueCustomerCollect customerCollect = clueCustomerCollectService.getOneByParam(collectRequest);
        if (EmptyUtils.isEmpty(customerCollect)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-线索客户宽表信息不存在");
        }

        ClueCustomerCollect updateCollectRequest = ClueCustomerCollectAssembler.initUpdateByFailInfo(request, followPlanResponse, clueFail);
        updateCollectRequest.setId(customerCollect.getId());
        int result = clueCustomerCollectService.update(updateCollectRequest);
        if (result <= 0) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-更新线索宽表数据信息失败");
        }
    }

    /**
     * 线索激活-判断是否可以激活
     *
     * @param request 参数
     * @param clue    线索信息
     */
    private void checkFailActive(UpdateClueEmpRequest request, Clue clue) {
        if (!FailStatusEnum.ACTIVATE.getCode().equals(request.getFailStatus())) {
            return;
        }
        CustomerResponse customerResponse = customerService.getDetailByIdAndDealerId(clue.getCusId(), clue.getDealerId());
        if (EmptyUtils.isEmpty(customerResponse)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败激活-客户信息不存在");
        }
        if (oemCustomerService.checkCustomerPhone(customerResponse.getPhone(), customerResponse.getDealerId(),customerResponse.getTenantId(),String.valueOf(customerResponse.getCorpId()))) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败激活-存在有效线索，不可以激活线索");
        }
    }

    @Override
    public List<ClueDictionariesResponse> getListDictionaries(Integer type) {
        ValidateUtils.checkObjNull(type, "输入参数错误");
        if (EmptyUtils.isEmpty(ClueDictionaryTypeEnum.getByCode(type))) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_INVALIDATE, "输入类型不存在");
        }
        if (ClueDictionaryTypeEnum.INTENTION.getCode().equals(type)) {
            return clueIntentionService.getClueIntentionDictionaries();
        }
        if (ClueDictionaryTypeEnum.CUSTOMER_INFO.getCode().equals(type)) {
            return customerService.getClueCustomerDictionaries();
        }
        throw new BusinessException(NEError.BUSINESS_ERROR, "未配置对应字典Type");
    }

    /**
     * 修改客户信息埋点
     * @param request
     */
    @Async
    @Override
    public void updateClueCustomerBackend(UpdateClueCustomerRequest request) {
        log.info("start updateClueCustomerBackend params:[{}]", JSON.toJSONString(request));
        UpdateCustomerRequest updateCustomer = request.getUpdateCustomer();
        ClueCustomerUpdateBackendRequest backendRequest = ClueCustomerUpdateBackendRequest.builder().qualification(updateCustomer.getEducation()).build();
        BeanUtil.copy(updateCustomer,backendRequest);
        //查询线索信息
        Clue clue = clueService.getDetailById(updateCustomer.getClueId());
        if (EmptyUtils.isEmpty(clue) || DeleteEnum.DETELED.getFlag().equals(clue.getDeleted())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "更新客户信息埋点-线索信息不存在");
        }

        GenderEnum genderEnum = GenderEnum.getByCode(updateCustomer.getGender());
        if(Objects.nonNull(genderEnum)){
            backendRequest.setGender(genderEnum.getName());
        }

        backendRequest.setUid(updateCustomer.getOneId());
        if(StringUtils.isNotBlank(clue.getDealerId()) && !"0".equals(clue.getDealerId())){
            /**
             * 查询经销商信息
             */
            String dealerName = getDealerName(clue.getDealerId());
            backendRequest.setDealerName(dealerName);
            backendRequest.setDealerId(clue.getDealerId());
        }

        ClueRecordBackendRequest<ClueCustomerUpdateBackendRequest> params = new ClueRecordBackendRequest();
        params.setParams(backendRequest);
        params.setUid(updateCustomer.getOneId());
        params.setUin(updateCustomer.getOneId());
        params.setEventCode(ClueEventLogEnum.UPDATE_CUSTOMER_SUCCEED_EVENT.getCode());
        params.setEventName(ClueEventLogEnum.UPDATE_CUSTOMER_SUCCEED_EVENT.getName());
        params.setEventTime(new Date().getTime());
        log.info("修改客户信息进行埋点，调用参数：【{}】",JSON.toJSONString(params));
        Response response = etlLogClient.backend(params);
        log.info("修改客户信息进行埋点，返回：【{}】",JSON.toJSONString(response));
    }

    /**
     * 线索跟进埋点（试乘试驾-交车）
     * @param request
     */
    @Async
    @Override
    public void clueFollowBackend(AddClueCustomerFollowRequest request) {
        log.info("start clueFollowBackend params:[{}]",JSON.toJSONString(request));
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if(Objects.isNull(request.getAddCustomerFollowRecord())){
            log.info("线索跟进埋点，线索跟进记录为空，不进行埋点");
            return;
        }
        if(StringUtils.isBlank(request.getAddCustomerFollowRecord().getFollowContent())){
            log.info("线索跟进埋点，线索跟进记录得跟进状态为空");
            return;
        }
        if(Objects.isNull(request.getAddCustomerFollowRecord().getCusId())){
            log.info("线索跟进埋点，线索跟进记录的客户ID为空");
            return;
        }
        //获取客户基本信息
        CustomerResponse customerResponse = customerService.getDetailByIdAndDealerId(request.getAddCustomerFollowRecord().getCusId(), null);
        if (EmptyUtils.isEmpty(customerResponse)) {
            throw new BusinessException(NEError.METHOD_ARGUMENT_EMPTY, "客户信息不存在");
        }
        //获取线索客户的意向信息
        String modelName = null;
        List<ClueToMqVehResponse> responseList = clueIntentionVehicleService.getListByClueId(request.getAddCustomerFollowRecord().getClueId());
        if(CollectionUtils.isNotEmpty(responseList)){
            ClueToMqVehResponse clue = responseList.get(0);
            modelName = clue.getModelName();
        }
        //查询线索信息
        Clue clue = clueService.getDetailById(request.getAddCustomerFollowRecord().getClueId());
        if (EmptyUtils.isEmpty(clue) || DeleteEnum.DETELED.getFlag().equals(clue.getDeleted())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索跟进进行埋点-线索信息不存在");
        }
        //获取客户经销商信息
        String dealerName = null;
        if(StringUtils.isNotBlank(clue.getDealerId()) && !"0".equals(clue.getDealerId())){
            /**
             * 查询经销商信息
             */
            dealerName = getDealerName(clue.getDealerId());
        }
        //下次跟进时间
        String planFollowTime = null;
        if(Objects.nonNull(request.getAddCustomerFollowPlan()) && Objects.nonNull(request.getAddCustomerFollowPlan().getPlanFollowTime())){
            planFollowTime = format.format(request.getAddCustomerFollowPlan().getPlanFollowTime());
        }

        int followContent = Integer.parseInt(request.getAddCustomerFollowRecord().getFollowContent());
        if(followContent == FollowContentEnum.DRIVE_TEST.getCode()){
            //试乘试驾

            String driveModelName = null;
            if (Objects.nonNull(request.getAddCustomerFollowRecord().getDriveModelId())) {
                //获取试乘试驾车型名称
                QueryVehicleModelRequest modelRequest = new QueryVehicleModelRequest();
                modelRequest.setId(request.getAddCustomerFollowRecord().getDriveModelId());
                Response<VehicleModelResponse> modelRes = mdQueryClient.getOneModelByParam(modelRequest);
                if (modelRes != null && modelRes.getData() != null) {
                    VehicleModelResponse model = modelRes.getData();
                    driveModelName = modelRes.getData().getName();
                }
            }


            ClueTestDriveRequest driveRequest = ClueTestDriveRequest.builder().modelId(modelName).clueStatus(ClueStatsEnum.CHECKIN.getCode())
                    .clueStatusName(ClueStatsEnum.CHECKIN.getName())
                    .operateTime(format.format(request.getAddCustomerFollowRecord().getOperateTime()))
                    .driveModelId(driveModelName)
                    .planFollowTime(planFollowTime).build();
            driveRequest.setUid(customerResponse.getOneId());
            driveRequest.setDealerId(clue.getDealerId());
            driveRequest.setDealerName(dealerName);

            ClueRecordBackendRequest<ClueTestDriveRequest> params = new ClueRecordBackendRequest();
            params.setParams(driveRequest);
            params.setUid(customerResponse.getOneId());
            params.setUin(customerResponse.getOneId());
            params.setEventCode(ClueEventLogEnum.TEST_DRIVE_SUCCEED_EVENT.getCode());
            params.setEventName(ClueEventLogEnum.TEST_DRIVE_SUCCEED_EVENT.getName());
            params.setEventTime(new Date().getTime());
            log.info("线索跟进-试乘试驾进行埋点，调用参数：【{}】",JSON.toJSONString(params));
            Response response = etlLogClient.backend(params);
            log.info("线索跟进-试乘试驾进行埋点，返回：【{}】",JSON.toJSONString(response));
        }else if(followContent == FollowContentEnum.DELIVERY.getCode()){
            //交车成功
            //查询下订订单信息
            ClueOrder order = new ClueOrder();
            order.setDeleted(DeleteEnum.INIT.getFlag());
            order.setClueId(request.getAddCustomerFollowRecord().getClueId());
            ClueOrderResponse clueOrder = clueOrderService.getOneByParam(order);
            String orderModelName = null;
            if(Objects.nonNull(clueOrder)){
                orderModelName = clueOrder.getOrderModelName();
            }

            ClueDeliveryRequest deliveryRequest = ClueDeliveryRequest.builder().modelId(modelName).clueStatus(ClueStatsEnum.DELIVERY.getCode())
                    .clueStatusName(ClueStatsEnum.DELIVERY.getName())
                    .createdTime(format.format(request.getAddCustomerFollowRecord().getOperateTime()))
                    .orderModelId(orderModelName)
                    .planFollowTime(planFollowTime).build();
            deliveryRequest.setUid(customerResponse.getOneId());
            deliveryRequest.setDealerId(clue.getDealerId());
            deliveryRequest.setDealerName(dealerName);

            ClueRecordBackendRequest<ClueDeliveryRequest> params = new ClueRecordBackendRequest();
            params.setParams(deliveryRequest);
            params.setUid(customerResponse.getOneId());
            params.setUin(customerResponse.getOneId());
            params.setEventCode(ClueEventLogEnum.DELIVERY_EVENT.getCode());
            params.setEventName(ClueEventLogEnum.DELIVERY_EVENT.getName());
            params.setEventTime(new Date().getTime());
            log.info("线索跟进-线索交车进行埋点，调用参数：【{}】",JSON.toJSONString(params));
            Response response = etlLogClient.backend(params);
            log.info("线索跟进-线索交车进行埋点，返回：【{}】",JSON.toJSONString(response));
        }
    }

    /**
     * 战败埋点（战败审核通过成功-战败激活）
     * @param request
     */
    @Async
    @Override
    public void clueFailFollowBackend(UpdateClueEmpRequest request) {
        log.info("start clueFailFollowBackend params:[{}]",JSON.toJSONString(request));
        //查询线索信息
        Clue clue = clueService.getDetailById(request.getClueId());
        if (EmptyUtils.isEmpty(clue) || DeleteEnum.DETELED.getFlag().equals(clue.getDeleted())) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败审批-线索信息不存在");
        }
        //查询客户信息
        CustomerResponse customerResponse = customerService.getDetailByIdAndDealerId(clue.getCusId(), clue.getDealerId());
        if (EmptyUtils.isEmpty(customerResponse)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "战败激活-客户信息不存在");
        }
        //查询客户经销商
        String dealerName = null;
        if(StringUtils.isNotBlank(clue.getDealerId()) && !"0".equals(clue.getDealerId())){
            dealerName = getDealerName(clue.getDealerId());
        }
        //获取线索客户的意向信息
        String modelName = null;
        List<ClueToMqVehResponse> responseList = clueIntentionVehicleService.getListByClueId(request.getClueId());
        if(CollectionUtils.isNotEmpty(responseList)){
            ClueToMqVehResponse clueToMqVehResponse = responseList.get(0);
            modelName = clueToMqVehResponse.getModelName();
        }

        FailStatusEnum failStatusEnum = FailStatusEnum.getByCode(request.getFailStatus());
        if (EmptyUtils.isEmpty(failStatusEnum)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索审批-线索状态枚举不存在");
        }
        ClueFail queryClueFail = new ClueFail();
        queryClueFail.setClueId(request.getClueId());
        queryClueFail.setDeleted(DeleteEnum.INIT.getFlag());
        queryClueFail.setStatus(request.getFailStatus());
        queryClueFail.setOrderFields(Lists.newArrayList(new OrderField("id", "DESC")));
        ClueFail clueFail = clueFailService.getOneByParam(queryClueFail);
        if (EmptyUtils.isEmpty(clueFail)) {
            throw new BusinessException(NEError.BUSINESS_ERROR, "线索审批-线索战败审批信息不存在");
        }
        if(request.getFailStatus().intValue() == FailStatusEnum.AGREE.getCode()){
            //同意战败
            //查询主数据战败主因名称
            QueryDictionariesRequest dictionariesRequest = new QueryDictionariesRequest();
            dictionariesRequest.setCode(clueFail.getFailReasonCodes());
            log.info("战败审核通过，查询战败主因，调用字典 参数={}", JSON.toJSONString(dictionariesRequest));
            Response<List<DictionariesResponse>> dicResponse = tenantClient.getDictionariesListByParam(dictionariesRequest);
            log.info("战败审核通过，查询战败主因，调用字典 返回={}", JSON.toJSONString(dicResponse));
            String failReason = null;
            if(Objects.nonNull(dicResponse) && dicResponse.getCode() == 0 && CollectionUtils.isNotEmpty(dicResponse.getData())){
                failReason = dicResponse.getData().get(0).getName();
            }
            ClueFollowFailAuditRequest auditRequest = ClueFollowFailAuditRequest.builder().modelId(modelName)
                    .clueStatus(ClueStatsEnum.IS_FAIL.getCode())
                    .clueStatusName(ClueStatsEnum.IS_FAIL.getName())
                    .failReasonCodes(clueFail.getFailReasonCodes())
                    .failReasonName(failReason)
                    .failRemark(clueFail.getFailRemark()).build();
            auditRequest.setUid(customerResponse.getOneId());
            auditRequest.setDealerId(clue.getDealerId());
            auditRequest.setDealerName(dealerName);

            ClueRecordBackendRequest<ClueFollowFailAuditRequest> params = new ClueRecordBackendRequest();
            params.setParams(auditRequest);
            params.setUid(customerResponse.getOneId());
            params.setUin(customerResponse.getOneId());
            params.setEventCode(ClueEventLogEnum.DEFEAT_AUDIT_EVENT.getCode());
            params.setEventName(ClueEventLogEnum.DEFEAT_AUDIT_EVENT.getName());
            params.setEventTime(new Date().getTime());
            log.info("线索战败审核通过进行埋点，调用参数：【{}】",JSON.toJSONString(params));
            Response response = etlLogClient.backend(params);
            log.info("线索战败审核通过进行埋点，返回：【{}】",JSON.toJSONString(response));
        }else if(request.getFailStatus().intValue() == FailStatusEnum.ACTIVATE.getCode()){
            ClueFollowActiveRequest activeRequest = ClueFollowActiveRequest.builder().modelId(modelName)
                    .clueStatus(ClueStatsEnum.FOLLOW_UP.getCode())
                    .clueStatusName(ClueStatsEnum.FOLLOW_UP.getName()).build();
            activeRequest.setUid(customerResponse.getOneId());
            activeRequest.setDealerId(clue.getDealerId());
            activeRequest.setDealerName(dealerName);

            ClueRecordBackendRequest<ClueFollowActiveRequest> params = new ClueRecordBackendRequest();
            params.setParams(activeRequest);
            params.setUid(customerResponse.getOneId());
            params.setUin(customerResponse.getOneId());
            params.setEventCode(ClueEventLogEnum.DEFEAT_ACTIVATION_EVENT.getCode());
            params.setEventName(ClueEventLogEnum.DEFEAT_ACTIVATION_EVENT.getName());
            params.setEventTime(new Date().getTime());
            log.info("线索战败激活进行埋点，调用参数：【{}】",JSON.toJSONString(params));
            Response response = etlLogClient.backend(params);
            log.info("线索战败激活进行埋点，返回：【{}】",JSON.toJSONString(response));
        }

    }

    @Override
    public CustomerResponse getCustomerByCusId(Long clueId) {
        //填充线索基本信息
        Clue clue = clueService.getDetailById(clueId);
        if (EmptyUtils.isEmpty(clue)) {
            throw new BusinessException(NEError.INVALID_PARAMETER, "线索信息不存在");
        }
        return customerService.getDetailByIdAndDealerId(clue.getCusId(), clue.getDealerId());
    }

    /**
     *
     * @param dealerId
     * @return
     */
    public String getDealerName(String dealerId){
        if(StringUtils.isBlank(dealerId)){
            return null;
        }
        Response<DealerResponse> dealerRes = mdQueryClient.getDetailById(Integer.parseInt(dealerId));
        if (Objects.nonNull(dealerRes) && dealerRes.getCode() == 0 && Objects.nonNull(dealerRes.getData())) {
            DealerResponse dealer = dealerRes.getData();
            return dealer.getName();
        }
        return null;
    }
}
